/* 
 * File:   AutoCommitTx.h
 * Author: sig-a
 *
 */

#ifndef INDEX_H
#define	INDEX_H

#include <cstdlib>
#include <string>
#include <map>
#include "contest_interface.h"
#include "Mutex.h"
#include "IndexSchema.h"
#include "QuadTree.h"

typedef struct Index {
public:
    /*Free Key*/
    void FreeKey(Key key);

    // Constructor
    Index(IndexSchema * inds);

    ~Index() {
    }

    Index() {
    }
    void Close();

    IndexSchema * getSchema() {
        return this->schema;
    }

    /*To handle the transactions*/
    ErrorCode EndTransaction(Transaction **tx) {
        return this->schema->EndTransaction(*tx);
    }

    void HandleTransaction(Transaction **tx) {
        this->schema->HandleTransaction(*tx);
    }

    ErrorCode TransactionCommitted(Transaction **tx) {
        return this->schema->executeTransaction(tx);
    }
    //    ErrorCode AutoCommitTransaction(Transaction ** tx)       //Added by Basmah Not Needed
    //    {
    //    }

    bool isClosed() {
        return this->closeFlag;
    }

    // Functions used to connect with QTree
    ErrorCode Insert(Transaction *tx, Record * _record);
    ErrorCode DeleteRecord(Transaction *tx, Record *r, uint8_t duplicateFlag, Iterator * it);
    ErrorCode UpdateRecord(Transaction *tx, Record *record, uint8_t flags,
            Iterator * it);
    ErrorCode Search(Transaction *tx, Key min, Key max, Iterator ** it);

private:
    bool closeFlag;
    IndexSchema* schema;
    Mutex mutex_;
} Index;

class map_indexes {
public:
    /*static*/
    static map_indexes& getInstance();

    ErrorCode insert(const char* name, IndexSchema * ix);
    ErrorCode deleteIndex(const char* name);

    bool test_existance(const char* name);
    IndexSchema* Find(const char* name);

    // Initialize the singleton instance of IndexManager
    static void Initialize();

    // Destroy the singleton instance of IndexManager
    static void Destroy();

private:
    static pthread_once_t once_;
    static map_indexes* single;
    std::map< std::string, IndexSchema*> mymap;

    // Private constructor (don't allow instanciation from outside)

    map_indexes() {
    };
    // Destructor

    ~map_indexes() {
    };
    // A pthread once handle to guarantee that the singleton instance is 
    // only initialized once

    Mutex mutex_;
    /*True if the index exist*/
};

//map_indexes index_manager;

#endif	/* INDEX_H */
